package com.example.demo;

import com.example.demo.util.FileListenAdaptor;
import com.example.demo.util.MyClassLoader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.net.URISyntaxException;

import static com.example.demo.constant.ApplicationConstant.LINUX_SEQ;

@SpringBootApplication
@Slf4j
public class DemoApplication implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) {
        try {
            // 监控文件,来自master的提交
            // 监控文件,来自deploy分支
            String classPath = MyClassLoader.class.getResource(LINUX_SEQ).toURI().getPath();
            IOFileFilter dirFilter = FileFilterUtils.and(FileFilterUtils.directoryFileFilter(), HiddenFileFilter.VISIBLE);
            IOFileFilter fileFilter = FileFilterUtils.and(FileFilterUtils.fileFileFilter(), FileFilterUtils.suffixFileFilter(".class"));
            IOFileFilter filter = FileFilterUtils.or(dirFilter, fileFilter);
            FileAlterationObserver observer = new FileAlterationObserver(classPath, filter, IOCase.SENSITIVE);

            FileListenAdaptor adaptor = new FileListenAdaptor();
            observer.addListener(adaptor);
            FileAlterationMonitor monitor = new FileAlterationMonitor(2000L, observer);
            //开启监控,来自deploy分支, master测试1
            //开启监控,来自deploy分支,测试1
            MyClassLoader.loadClassPath();
            monitor.start();
        } catch (ClassNotFoundException e) {
            log.error("load class error: ", e);
        } catch (Exception e) {
            log.error("程序启动失败！", e);
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class);
    }
}
